package com.next

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_HEAD_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_PRODUCT_MANAGER', 'ROLE_SECOND_BRANCH_OFFICE_PRODUCT_MANAGER',
    'ROLE_SECOND_BRANCH_OFFICE_DIRECTOR', 'ROLE_ACCOUNT_MANAGER', 'ROLE_SALES_REPRESENTATIVE', 'ROLE_BANK_OUTLETS_ADMINISTRATOR', 'ROLE_MERCHANT_ADMINISTRATOR', 'ROLE_CHANNEL_ADMINISTRATOR'])
@Transactional(readOnly = true)
class BocAccountController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def max = params.max
        def offset = params.offset

        def type = AccountType.findByName("机构")
        def name = params['name']
        def code = params['code']
        def levelId = params['levelId']
        def level
        def active = params['active']
        String sql = "from Account where type.id = ${type.id}"
        if (name)
        {
            sql += " and name like '%${name}%'"
        }
        if (code)
        {
            sql += " and code like '%${code}%'"
        }
        if (levelId)
        {
            level = AccountLevel.findById(params['levelId'])
            sql += " and level.id = ${level.id}"
        }
        if (active)
        {
            sql += " and active = ${active}"
        }
        def list = Account.findAll(sql, [max: max, offset: offset])
        def count = Account.executeQuery("select count(id) " + sql)[0]

        respond list, model: [accountCount: count, params: params], view: 'index'
    }

    def show(Account account)
    {
        def subAccounts = Account.findAllByParentAndType(account, AccountType.findByName('机构'))
        def accountTeam = AccountTeam.findAllByAccount(account)
        respond account, model: [subAccounts: subAccounts, accountTeam: accountTeam]
    }

    def create()
    {
        respond new Account(params)
    }

    @Transactional
    def save(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'create'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'show', id: account?.id
            }
            '*' { respond account, [status: CREATED] }
        }
    }

    def edit(Account account)
    {
        respond account
    }

    @Transactional
    def update(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (params.districtName)
        {
            account.district = District.findByName(params.districtName)
        }
        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'edit'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'show', id: account?.id
            }
            '*' { respond account, [status: OK] }
        }
    }

    @Transactional
    def delete(Account account)
    {

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        account.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'account.label',
                                                                                          default: 'Account'), params
                    .id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    // 渠道
    def channelIndex()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def max = params.max
        def offset = params.offset

        def type = AccountType.findByName("渠道")
        // def type = AccountType.findByName(params['type'])
        def name = params['name']
        def code = params['code']

        String sql = "from Account where type.id = ${type.id}"
        if (name)
        {
            sql += " and name like '%${name}%'"
        }
        if (code)
        {
            sql += " and code like '%${code}%'"
        }

        def list = Account.findAll(sql, [max: max, offset: offset])
        def count = Account.executeQuery("select count(id) " + sql)[0]

        respond list, model: [accountCount: count, params: params], view: 'channelIndex'
    }

    def channelCreate()
    {
        respond new Account(params)
    }

    @Transactional
    def channelSave(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'channelCreate'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'channelShow', id: account?.id
            }
            '*' { respond account, [status: CREATED] }
        }
    }

    def channelEdit(Account account)
    {
        respond account
    }

    @Transactional
    def channelUpdate(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (params.districtName)
        {
            account.district = District.findByName(params.districtName)
        }
        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'channelEdit'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'channelShow', id: account?.id
            }
            '*' { respond account, [status: OK] }
        }
    }

    def channelShow(Account account)
    {
        def accountTeam = AccountTeam.findAllByAccount(account)
        respond account, model: [accountTeam: accountTeam]
    }

    // 商户
    def merchantIndex()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def max = params.max
        def offset = params.offset

        def type = AccountType.findByName("商户")
        // def type = AccountType.findByName(params['type'])
        def name = params['name']
        def code = params['code']
        def parentId = params['parentId']
        def parent
        def active = params['active']

        String sql = "from Account where type.id = ${type.id}"
        if (name)
        {
            sql += " and name like '%${name}%'"
        }
        if (code)
        {
            sql += " and code like '%${code}%'"
        }
        if (parentId)
        {
            parent = Account.findById(params['parentId'])
            sql += " and parent.id = ${parent.id}"
        }
        if (active)
        {
            sql += " and active = ${active}"
        }

        def list = Account.findAll(sql, [max: max, offset: offset])
        def count = Account.executeQuery("select count(id) " + sql)[0]

        respond list, model: [accountCount: count, params: params], view: 'merchantIndex'
    }

    def merchantCreate()
    {
        respond new Account(params)
    }

    @Transactional
    def merchantSave(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'merchantCreate'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'merchantShow', id: account?.id
            }
            '*' { respond account, [status: CREATED] }
        }
    }

    def merchantEdit(Account account)
    {
        respond account
    }

    @Transactional
    def merchantUpdate(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }
        if (params.districtName)
        {
            account.district = District.findByName(params.districtName)
        }
        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'merchantEdit'
            return
        }

        account.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'account.label',
                                                                                        default: 'Account'), account
                    .id])
                redirect action: 'merchantShow', id: account?.id
            }
            '*' { respond account, [status: OK] }
        }
    }

    def merchantShow(Account account)
    {
        def accountTeam = AccountTeam.findAllByAccount(account)
        def productAccounts = ProductAccount.findAllByAccount(account)
        respond account, model: [accountTeam: accountTeam, productAccounts: productAccounts]
    }

}
